#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "get_ID.h"

#define PATH_2 "/proc/cpuinfo"

/*struct rpi_ID_s
{
	char  ID[12];
};

int get_ID(struct rpi_ID_s *rpi_ID);
int main (int argc,char ** argv)
{
        int                     rv=-1;
	struct                  rpi_ID_s  rpi_ID;

	memset(&rpi_ID, 0, sizeof(rpi_ID));
	rv = get_ID(&rpi_ID);
	if(rv<0)
	{
		printf("get ID failure,return value:%d\n",rv);
		return -2;
	}
	printf("ID:%s\n",rpi_ID.ID);
}
*/
int get_ID(struct rpi_ID_s *rpi_ID)
{
	int 		        fd=-1;
	char 		        buf[2048];
	char	       	       *str=NULL;
	char                   *ptr=NULL;
	char                   *rtr=NULL;
	int			found=0;
	int                     i=0;
	int                     rv=-1;
	
	memset(buf,0,sizeof(buf));	

	fd = open(PATH_2, O_RDONLY);
	if (!fd)
	{
		perror("FILE problem");
		return -1;
	}
	
	rv=read(fd,buf,sizeof(buf));
	if(rv<0)
	{
		printf("Read failure:%s\n", strerror(errno));
		return -2;
	}
	
	str=strstr(buf,"Hardware");
	if(!str)
	{
		printf("can't not find string\n");
		return -3;
	}
	
	ptr=strstr(str,"B");
	if(!str)
	{
		printf("can't not find string\n");
		return -4;
	}

	rtr=strstr(ptr,"R");
	if(!str)
	{
		printf("can't not find string\n");
		return -5;
	}


	strncpy(rpi_ID->ID, ptr, strlen(ptr)-strlen(rtr));
	close(fd);
	return 0;
}

